package icraf.carbon.gui.chart;

import icraf.carbon.core.AbacusData;

import java.awt.BasicStroke;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.Rectangle2D;
import java.awt.geom.RoundRectangle2D;

import javax.swing.JPanel;

public class AbacusLabel extends JPanel {

		private static final long serialVersionUID = 6291986603840178019L;
		AbacusBar bar;
		
		private LabelFormat labelFormat = new LabelFormat();
		private BasicStroke lineStroke = null;
		private float relativeX;
		private float relativeY;
		
		public LabelFormat getLabelFormat() {
			return labelFormat;
		}

		public void setLabelFormat(LabelFormat labelFormat) {
			this.labelFormat = labelFormat;
			lineStroke = labelFormat.generateStroke();
			updateSize();
		}


		public AbacusLabel(AbacusBar b) {
			this.bar = b;
			b.setLabel(this);
		}

		public AbacusBar getBar() {
			return bar;
		}

		public String getText() {
			if (bar == null)
				return "";
			AbacusData d = bar.getData();
			String s = d.getLabel1() + " -> "
					+ d.getLabel2();
			return s;
		}

		public void paint(Graphics g) {
			Graphics2D g2 = (Graphics2D) g;
			g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
					RenderingHints.VALUE_ANTIALIAS_ON);
			Dimension dim = getSize();
			FontMetrics fm = getFontMetrics(labelFormat.font);
			Rectangle2D d = fm.getStringBounds(getText(), this.getGraphics());
			
			float cor = labelFormat.corner;
			float l = labelFormat.lineSize;
			RoundRectangle2D rec = new RoundRectangle2D.Float(l/2, l/2, dim.width-l, dim.height-l, cor, cor);
			g2.setColor(labelFormat.fillColor);
			g2.fill(rec);
			if (labelFormat.lineSize > 0) {
				g2.setColor(labelFormat.lineColor);
				g2.setStroke(lineStroke);
				g2.draw(rec);
			}
			
			g2.setFont(labelFormat.font);
			g2.setColor(labelFormat.fontColor);
			g2.drawString(getText(), 7+l, (int)(dim.getHeight()/2+d.getHeight()/3));
		}

		public void updateSize() {
			FontMetrics fm = getFontMetrics(labelFormat.font);
			Rectangle2D d = fm.getStringBounds(getText(), this.getGraphics());
			int l = (int)labelFormat.lineSize;
			this.setSize((int) d.getWidth() + 12+ 2*l, (int) d.getHeight() + 6 + 2*l);
		}

		@Override
		public void setLocation(int x, int y) {
			Dimension dim = this.getParent().getSize();
			relativeX = (float)x/(float)dim.width;
			relativeY = (float)y/(float)dim.height;
			super.setLocation(x, y);
		}
		
		public float getRelativeX() {
			return relativeX;
		}

		public float getRelativeY() {
			return relativeY;
		}

		public void updateRelativeLocation() {
			Dimension dim = this.getParent().getSize();
			setLocation((int)(relativeX*dim.width), (int)(relativeY*dim.height));
		}
	}